#!/bin/bash

set -x
logthis=./log/$(basename $0).log
echo logthis
exec 3>&1
exec 1>$logthis 2>&1


#cd evdev-1.6.1
#python setup.py install
#cd ..
#sleep 1 
./test_path


echo "beagleV-AHead factory test"
date
uname -a

jigNo=1

TRIES=3
eepid=


# ./leds -t 1000 4 &
# pid_leds=$!

python3 set_time.py
./leds all on
for (( i = 0; i < $TRIES; i++ )); do
	eepid=$(python3 barcode.py)
  # eepid=BVAH202322000964
	if [[ "$eepid" =~ ^[a-zA-Z]{4}[0-9]{12}$ ]]; then
		break
	fi
done
if [ $i -ge $TRIES ]; then
	exit 1
fi
# kill -9 "$pid_leds"
./leds all off

result=0
max_attempts=5
scripts=("test_p8" "test_p9" "test_eth0" "test_mikbus_rp2040" "test_wifi" "test_eeprom"  "test_microsd" "test_cam0" "test_cam1" "test_bt" "test_swusb" "test_swtf")

for script in "${scripts[@]}"
do
  attempts=0
  exit_code=1
  while [ "$exit_code" -ne 0 ] && [ "$attempts" -lt "$max_attempts" ]
  do
    [ $attempts -ge 1 ] && { sleep 3; }
    echo -e "\n------------Script Name: $script, Excute Time: $((attempts + 1))---------------\n"
    bash "$script"
    exit_code=$?
    attempts=$((attempts + 1))
  done

  if [ "$exit_code" -ne 0 ]; then
    echo "$script FAIL"
    result=$((result + 1))
  else
    echo "$script PASS"
  fi
done

now=`TZ='Asia/Shanghai' date +"%Y%m%d-%H%M%S"`
echo "result= $result"
if [ "$result" -eq 0 ];then
    echo -e "\n--------------------ALL TEST PASS------------------\n"
    logName="102991698_${eepid}_S1_J${jigNo}_OK_T${now}.log"
else
    echo -e "\n--------------------ALL TEST FAIL------------------\n"
    logName="102991698_${eepid}_S1_J${jigNo}_FAIL_T${now}.log"
fi

for (( i = 0; i < 100; i++ )); do
    python3 alicloud_upload.pyc "$logName" "$logthis"
    r=$?
    [ "$r" -eq 0 ] && break
done

if [ "$result" -eq 0 ];then
	./leds all on
	sleep 1
	# poweroff
else
	while [ 1 ]
	do
		./leds all on
		sleep 0.1
		./leds all off
		sleep 0.1
	done

fi




